How to use square bracket([]) Notation In Typescript

In this approach, we are using square bracket([]) Notation to access the private members of the Class. We have defined the private variable as data3 and the private function as privateFn in GFGClass3. We are accessing this member using [] notation and type assertion to any.

Syntax:

const value = (object as any)['propertyName'];

Example: Below is the implementation of the above-discussed approach.

Javascript
class GFGClass3 {
  private data3: string = 
  'This is Private Variable';
  private privateFn(): void {
    console.log(
    'This is Private Function Called');
  }
  public accessFn3() {
    const privateVar = 
    (this as any)['data3'];
    console.log(privateVar);
    const privateFunction = 
    (this as any)['privateFn'];
    privateFunction.call(this);
  }
}
const myObject = new GFGClass3();
myObject.accessFn3();

Output:

"This is Private Variable" 
"This is Private Function Called"

How to Access TypeScript Private Members ?

In this TypeScript article, we will learn how to access the TypeScript private members using different approaches. We can interact with the encapsulated components within the class and access them in the application.

There are three different approaches through which we can access TypeScript private members.

Table of Content

  • Using any Type
  • Using Reflect
  • Using square bracket([]) Notation
  • Using ES6 WeakMap

Similar Reads

Using any Type

In this approach, we are using any Type to access private members. In the example, we have privateVar in the GFGClass which is accessed using any type assertion by bypassing the TypeScript’s encapsulation....

Using Reflect

In this approach, we are using Reflect to access private members. We have a private member as data2 in the GFGClass2 which is accessed using Reflect.get(this, ‘data2’). This approach reflects on the object instance to retrieve the value of the private member....

Using square bracket([]) Notation

In this approach, we are using square bracket([]) Notation to access the private members of the Class. We have defined the private variable as data3 and the private function as privateFn in GFGClass3. We are accessing this member using [] notation and type assertion to any....

Using ES6 WeakMap

In this approach, we utilize ES6 WeakMap to access private members. WeakMap allows us to store key-value pairs where the keys are objects and the values can be arbitrary data. We can use WeakMap to store private members and access them indirectly using class methods....